<template>
  <div class="picker-container">
    <van-cell
      :title="title"
      :border="border"
      :title-width="titleWidth"
      :required="required"
      :value-class="valueClass"
      :error-message="errorMessage"
      :error="error"
    >
      <picker
        mode="selector"
        @change="bindPickerChange"
        @cancel="bindPickerCancel"
        :value="index"
        :range="dataArray"
        :range-key="contentColumn"
        ref="content"
      >
        <slot name="content">
          <view
            class="picker-value"
            :class="[{'picker-value__error': error}]"
          > {{content?contentText:placeholder}} </view>
        </slot>
      </picker>
    </van-cell>
  </div>
</template>

<script>
// import Vue from 'vue'
export default {
  props: {
    label: {
      required: true,
      default: '字段名称'
    },
    // 选项数组
    data: {
      required: true,
      type: Array
    },
    // 默认选项
    contentColumn: {
      type: String,
      default: ''
    },
    // 默认选项
    valueColumn: {
      type: String,
      default: ''
    },
    // 默认选项
    value: {
      type: String,
      default: ''
    },
    errorMessage: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    titleWidth: {
      type: String
    },
    valueClass: {
      type: String
    },
    error: {
      type: Boolean,
      default: false
    },
    required: Boolean,
    border: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      title: '',
      content: '',
      contentText: '',
      dataArray: [],
      index: 0
    }
  },
  mounted () {
    console.log(this.data)
    this.dataArray = this.data
    if (this.value) {
      this.index =
        this.data.indexOf(this.value) !== -1
          ? this.data.indexOf(this.value)
          : 0
    }
    this.content = this.value
    //
    this.title = this.label
  },

  onLoad (option) {
    console.log('_____________onLoad')
  },
  created () {
    console.log('_____________created')
  },

  methods: {
    notice () {
      this.$emit('change', this.content)
    },
    bindPickerChange (e) {
      console.log(e)
      this.index = e.mp.detail.value
      const checkedItem = this.dataArray[this.index]
      this.content = checkedItem
      this.contentText = checkedItem
      if (typeof (checkedItem) === 'object') {
        if (this.contentColumn) {
          this.contentText = checkedItem[this.contentColumn]
        }
        if (this.valueColumn) {
          this.content = checkedItem[this.valueColumn]
        }
      }
      this.notice()
    },
    bindPickerCancel (e) {
      this.notice()
    }
  }
}
</script>

<style lang="less">
.picker-value__error {
  color: #ee0a24;
}
</style>